package org.springframework.web.servlet.mvc.method.annotation;

import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;

import java.lang.annotation.Annotation;

/**
 * @Author:liruo
 * @Date:2023-06-09-23:35:45
 * @Desc
 */
public class ServletModelAttributeMethodProcessorX extends ServletModelAttributeMethodProcessor {
    public ServletModelAttributeMethodProcessorX(boolean annotationNotRequired) {
        super(annotationNotRequired);
    }
    protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
        for (Annotation ann : parameter.getParameterAnnotations()) {
            //如果有@Validated就不校验
            if (ann.annotationType().isAssignableFrom(Validated.class)) {
                return;
            }

            //无@Validated
            Class<? extends Annotation> annotationType = ann.annotationType();
            String annotationName = annotationType.getName();
            Object[] validationHints = null;
            if ("javax.validation.Valid".equals(annotationName)) {
                validationHints = new Class[0];
            }
            if (annotationType.getSimpleName().startsWith("Valid")) {
                Object hints = AnnotationUtils.getValue(ann);
                validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
            }
            if (validationHints != null) {
                binder.validate(validationHints);
                break;
            }
        }
    }
}
